package com.android.volley.codec;



import com.android.volley.socket.SocketClient;

import java.io.File;

import javax.crypto.Cipher;

/**
 * Created by yinzhiqun on 2015/12/4.
 *
 */
public class YQDecoder extends Coder implements Decoder {
    private YQKey key;

    public YQDecoder(YQKey key) {
        this.key = key;
    }

    @Override
    public byte[] decode(byte[] data,boolean base64){
        if (data.length<6){//需要重置秘钥的有效期，下次重新获取
            key.setExpires(System.currentTimeMillis());
            File file = new File(SocketClient.filesDir + "/key");//本地保存的秘钥也要删除
            if (file.exists()){
                file.delete();
            }

            return "服务器找不到appid".getBytes();
        }

        byte[] prefix = new byte[6];
        System.arraycopy(data,0,prefix,0,6);
        if ("SECRET".equals(new String(prefix))){
            //前6个字节是secret，说明有经过加密
            try {
//                Log.w("kids", "解密操作, base64: "+base64);
                byte[] bytes = new byte[data.length - 6];
                System.arraycopy(data, 6, bytes, 0, bytes.length);

                Cipher cipher = Cipher.getInstance("DES");
                cipher.init(Cipher.DECRYPT_MODE, key.getSecretKey());

                if (base64){
                    return cipher.doFinal(decryptBASE64Byte(bytes));
                }else {
                    return cipher.doFinal(bytes);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return data;
    }
}
